package com.example.myproject.config;
import com.turn.ttorrent.tracker.Tracker;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.net.InetAddress;
import java.net.InetSocketAddress;

import com.turn.ttorrent.tracker.TrackedTorrent;
@Component
public class TrackerHolder {
    private Tracker tracker;

    public Tracker getTracker() {
        return tracker;
    }

    @PostConstruct
    public void init() {
        try {
            int trackerPort = 6969;
            String localIp = InetAddress.getLocalHost().getHostAddress();
            String announceURL = "http://" + localIp + ":" + trackerPort + "/announce";
            tracker = new Tracker(trackerPort, announceURL);


            File torrentDir = new File("torrents/");
            if (!torrentDir.exists()) torrentDir.mkdirs();

            File[] torrents = torrentDir.listFiles((dir, name) -> name.endsWith(".torrent"));
            if (torrents != null) {
                for (File f : torrents) {
                    tracker.announce(TrackedTorrent.load(f));
                    System.out.println("已加载种子：" + f.getName());
                }
            }

            tracker.start(true);
            System.out.println("Tracker 启动成功，监听端口：6969");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}